import Axios from "axios";
import QS from "qs";

import store from "../store";

const BaseUrl = "https://www.sinomarinetech.com/tjpsc";
const TimeOut = 1000 * 60;

const AxiosInstance = Axios.create(
    {
        baseURL: BaseUrl,
        timeout: TimeOut
    }
);



AxiosInstance.interceptors.request.use(
    config => {

        if (config.headers['Content-Type'] && config.headers['Content-Type'] === "application/x-www-form-urlencoded") {
            config.data = QS.stringify(config.data);
        }

        const accountToken = store.getState().get("accountReducer").get("accountToken");
        console.log("这是token=> "+accountToken);

        if (accountToken) {
            console.log("请求携带token");
            config.headers['AccountToken'] = accountToken; // 让每个请求携带token
        }else {
            console.log("请求未携带token");
        }

        return config;
    },
    error => {
        console.log("拦截器异常");
        console.log(error);
        Promise.reject(error);
    }
);

Axios.interceptors.response.use(response => {
    const code = response.data.status;

    console.log("获取响应"+response);

    if (code === 4000 || code === 4001) {
        console.log("退出登录");
        // // 登出操作
        // cookie.remove("tjUserInfo");
        // router.push({name: "login"});
        const history = this.props.history;
        console.log(history);
        history.push("/login")
    } else if (code === 4003) {
        console.log("code = 4003");
        return response.data
    } else {
        if (!response.data.resultStatus) {
            let _urls = response.config.url.split('/');
            let _url = _urls[_urls.length - 1];
            console.log("失败链接==>" + _url);

        }
        return response.data
    }
}, err => {
    console.log('响应体出现错误');
    return Promise.reject(err);
});


export default AxiosInstance;